package com.sy.core.web.system;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sy.core.model.SysRole;
import com.sy.core.model.SysUser;
import com.sy.core.model.common.TreeNode;
import com.sy.core.service.SysUserService;
import com.sy.core.util.BaseUUID;
import com.sy.core.util.ExcelExportUtil;
import com.sy.core.util.RestResult;
import com.sy.core.web.BaseCtl;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 	TODO 请用一句话描述该类的作用
 * @author CaiXinChong email:1060296473@qq.com
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/sysUser")
public class SysUserCtl extends BaseCtl {

    @Autowired
    private SysUserService  sysUserService;
    

	@RequestMapping("/{path}")
	public ModelAndView toAnyPage(@PathVariable String path,ModelAndView mv){
	    mv.setViewName(path);
	    return mv;
    }
    
    /**
     * Action for Add
     */
    @RequestMapping(value = "/save",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult save(SysUser sysUser,String jsonstr){
        RestResult rr = null;
        sysUser = JSONObject.parseObject(jsonstr,SysUser.class);
        String pk = sysUser.getPk();
        try {
            if(pk==null||pk.equals("")){
                pk = BaseUUID.getUUID();
                sysUser.setPk(pk);
                sysUserService.insert(sysUser);
            }else{
                if(sysUser.getRolePk().equals("")) sysUser.setRolePk("-1");
                sysUserService.update(sysUser);
            }
            rr = new RestResult("200","SUCCESS",pk);
        } catch (Exception e) {
            e.printStackTrace();
            rr = new RestResult("201","FAILED");
        }
        return rr;
    }

    /**
     * Action for update
     */
    @RequestMapping(value = "/update",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult update(SysUser sysUser){
         sysUserService.update(sysUser);
        return new RestResult("200","SUCCESS");
    }
    
    /**
     * Action for SelectOneByKey
     */
    @RequestMapping(value = "/query/{key}",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult queryByPrimaryKey(@PathVariable String key){
       try{
            SysUser sysUser = sysUserService.queryByPrimaryKey(key);
      	 	return new RestResult("200","SUCCESS",sysUser);
       }catch(Exception e){
    	   	logger.error("Query Model SysUser By PrimaryKey Is Fail:"+e.getMessage());
       }
       		return new RestResult("201","FAIL");
    }
    
    /**
     * Action for SelectList
     */
    @RequestMapping(value = "/list",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult queryList(SysUser sysUser,String str){
        sysUser = JSONObject.parseObject(str,SysUser.class);
        JSONObject json = JSONObject.parseObject(str);
       try{
           PageHelper.startPage(Integer.parseInt(json.getString("currentPage")),Integer.parseInt(json.getString("pageSize")));
      		List<SysUser> sysUserList = sysUserService.queryByCondition(sysUser);
      		PageInfo<SysUser> info = new PageInfo<>(sysUserList);
      	 	return new RestResult("200","SUCCESS",info);
       }catch(Exception e){
    	   logger.error("Query Model SysUser List Fail :"+e.getMessage());
       }
        return new RestResult("201","FAIL");
    }
    
    /**
     * Action for DeleteModel
     */
    @RequestMapping(value="/delete/{pks}",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult delete(@PathVariable String pks){
        RestResult rr =null;
        try {
            sysUserService.batchDelete(pks);
            rr=new RestResult("200","SUCCESS") ;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FAILED"+e.toString());
            rr=new RestResult("200","FAILED");
        }
        return rr;
    }

    /**
     * 获取角色树
     */
    @RequestMapping(value="/getRoleTree",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResult getRoleTree(TreeNode treeNode){
        RestResult rr =null;
        List<TreeNode> treeNodeList = new ArrayList<>();
        try {
            TreeNode node=null;
            List<SysRole> sysRoleList = sysRoleService.queryByCondition(null);
            for (int i = 0; i <sysRoleList.size() ; i++) {
                node=new TreeNode();
                node.setPk(sysRoleList.get(i).getPk());
                node.setLabel(sysRoleList.get(i).getName());
                node.setPcode("1");
                treeNodeList.add(node);
            }
            treeNode.setPcode("0");
            treeNode.setPk("1");
            treeNode.setLabel("所有角色");
            treeNode.setChildren(treeNodeList);
            treeNode.setDisabled(true);
            rr=new RestResult("200","SUCCESS",treeNode) ;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FAILED"+e.toString());
            rr=new RestResult("200","FAILED");
        }
        return rr;
    }

    /**
     * 获取选中的树的节点pk
     */
    @GetMapping("/getSelectedTree/{pk}")
    @ResponseBody
    public RestResult getSelectedTree(@PathVariable String pk){
        RestResult rr = null;
        try {
            SysUser sysUser = sysUserService.queryByPrimaryKey(pk);
            String[] rolePks=sysUser.getRolePk().split(",");
            rr=new RestResult("200","Success",rolePks);
        } catch (Exception e) {
            logger.error("Failed",e);
            rr=new RestResult("200","Failed");
        }
        return rr;
    }

    /**
     * 导出报表
     */
    @GetMapping("export")
    public void download(HttpServletResponse response){
        //1.构造数据
        List<SysUser> list =sysUserService.queryByCondition(null);
        //2.加载模板流数据
        Resource resource = new ClassPathResource("excel-template/sysUserTemplate.xlsx");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(resource.getFile());
            new ExcelExportUtil(SysUser.class,2,2).export(response,fis,list,"人员报表.xlsx");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出pdf
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/exportPdf")
    public void createPdf(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //1.引入jasper文件
        Resource resource = new ClassPathResource("templetes/test.jasper");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //2.创建JasperPrint,向jasper文件中填充数据
        ServletOutputStream os = response.getOutputStream();
        try {
            HashMap parameters = new HashMap();
            //构造javaBean数据源

            JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(getUserList());
            /**
             * 1.jasper文件流
             * 2.参数列表
             * 3.JRBeanCollectionDataSource
             */
            JasperPrint print = JasperFillManager.fillReport(fis, parameters,ds);
            //3.将JasperPrint已PDF的形式输出
            JasperExportManager.exportReportToPdfStream(print,os);
            response.setContentType("application/pdf");
        } catch (JRException e) {
            e.printStackTrace();
        }finally {
            os.flush();
        }
    }

    //创建数据库Connection
    public List<Map<String,String>> getUserList() throws Exception {
        List<SysUser> sysUsers = sysUserService.queryByCondition(null);
        List<Map<String,String>> list = new ArrayList<>();
        for(SysUser sysUser:sysUsers){
            Map<String,String> map = new HashMap<>();
            map.put("name",sysUser.getName());
            map.put("sex",sysUser.getSex()==1?"男":"女");
            map.put("account",sysUser.getAccount());
            map.put("birthday",sysUser.getBirthday());
            map.put("phone",sysUser.getPhone());
            map.put("email",sysUser.getEmail());
            list.add(map);
        }
        return list;
    }
}
